<?php

namespace app\user\logic;


use app\model\PigHealth;

class PigHealthEatLogic
{
    /**
     * @Description 统计
     * @author: zj
     * @param array $param
     * @time 2024/03/28 10:36:05
     * @return array
     */
    public function statistic(array $param)
    {
        $factory_id = request()->user_info['factory_id'];

        $model = new PigHealth();
        $startTime = strtotime(date('Y-m-d 00:00:00',strtotime($param['record_time_start'])));
        $endTime = strtotime(date('Y-m-d 00:00:00',strtotime($param['record_time_end'])));
        $days = ceil(($endTime - $startTime)/86400);

        $data = [];
        for($i = 0;$i<=$days;$i++) {
            $start_time = $startTime + $i * 86400;
            $end_time = $start_time + 86399;
            $health = $model->where('factory_id',$factory_id)
                ->field('avg(temperature) as temperature,avg(heart_rate) as heart_rate,avg(sao2) as sao2,avg(pi) as pi,avg(breathe) as breathe')
                ->where('pig_id',$param['pig_id'])
                ->where('record_time','>=',$start_time)
                ->where('record_time','<=',$end_time)
                ->where('delete_time',$model::IS_DELETE_NO)
                ->find();

                $data[] = [
                    'date' => date('Y-m-d',$start_time),
                    'temperature' => $health['temperature'] ? round($health['temperature'],2) : 0,
                    'heart_rate' => $health['heart_rate'] ? round($health['heart_rate'],2) : 0,
                    'sao2' => $health['sao2'] ? round($health['sao2'],2) : 0,
                    'pi' => $health['pi'] ? round($health['pi'],2) : 0,
                    'breathe' => $health['breathe'] ? round($health['breathe'],2) : 0,
                ];
        }

        return $data;
    }

}